<?php

namespace app\api\library;

use adjust\SendS2sAdjust;
use app\api\controller\Distributionuser;
use app\api\model\AppBaseConfig;
use app\api\model\UserBank;
use app\api\model\UserInfo;
use app\api\model\UserLoginLog;
use app\common\controller\api\Base;
use super\Http;
use think\Exception;
use think\exception\DbException;
use think\Request;
use super\Random;
use think\Cache;
use app\api\model\User;


class Auth
{
    protected $_error = '';

    protected $_error_code = 0;
    protected $logined = false; //登录状态
    protected $username;
    protected $keepTime = 2592000;


    public function __get($name)
    {
        return Cache::store('redis')->get('api.' . $name);
    }

    /**
     * 老系统用户同步
     */
    public function syncUser($username, $res)
    {
        //检索客服
        $personnelInfo = \app\api\model\CustomerServicePersonnel::get(['name' => $res['data']['uinfo']['kfname']]);
        if ($personnelInfo) {
            //获取客服开启的账号
            $account = \app\api\model\CustomerServiceAccount::field('id')->where([
                'customer_service_personnel_id' => $personnelInfo['id'],
                'status' => 1,
                'switch' => 1,
                'app_base_id' => 15,
                'is_del' => 0
            ])->find();
            if ($account) {
                //获取客服中间表信息
                $accountMiddle = \app\api\model\CustomerServiceAccountMiddle::get(['customer_service_account_id' => $account['id']]);
                if ($accountMiddle) {
                    $accountMiddleId = $accountMiddle['id'];
                }
            }
        }

        if (!empty($accountMiddleId)) {
            //映射当前状态
            $current_status = [
                1 => 1,
                2 => 1,
                3 => 3,
                4 => 4,
                5 => 5,
                6 => 6,
                7 => 7,
                8 => 20,
                9 => 21,
                10 => 22,
                11 => 23,
                13 => 25,
                14 => 32,
                22 => 25,
                23 => 26,
                24 => 27
            ];
            $params['salt'] = Random::alnum();
            //进行用户信息添加
            $setUserData = [
                'username' => $username,
                'password' => md5(md5('123456') . $params['salt']),
                'salt' => $params['salt'],
                'mobile' => $username,
                'avatar' => '',
                'joinip' => request()->ip(),
                'jointime' => time(),
                'source' => 1,
                'app_base_id' => 15,
                'channel' => '',
                'customer_service_account_middle_id' => $accountMiddleId,
                'country_config_id' => 1,
                'diff_time' => timeZoneConvert(1),
                'current_status' => $current_status[$res['data']['uinfo']['now_status']]
            ];

            //进行用户添加
            \app\api\model\User::create($setUserData);
            $user = \app\admin\model\User::get(['username' => $username, 'app_base_id' => 15]);

            $userId = $user['id'];
            //检索用户信息填写
            if (!empty($res['data']['submitinfo']['personal'])) {
                $personnel = $res['data']['submitinfo']['personal'];
                $setUserInfoData = [
                    'pincode' => $personnel['pincode'],
                    'education' => $personnel['education'],
                    'sex' => ($personnel['gender'] == 1) ? 'Male' : 'Female',
                    'country_config_id' => 1,
                    'source' => 1,
                    'type' => 34,
                    'current_address' => $personnel['address'],
                    'aadhaar_number' => $personnel['idcard'],
                    'marriage' => $personnel['marital'],
                    'name' => $personnel['name'],
                    'app_base_id' => 15,
                    'age' => $personnel['age'],
                    'email' => $personnel['email']
                ];
                $setUserInfo = [
                    'user_id' => $userId,
                    'source' => 1,
                    'app_base_id' => 15,
                    'type' => 34,
                    'info_json' => json_encode($setUserInfoData)
                ];
                UserInfo::create($setUserInfo);
            }
            //检索用户工作信息填写
            if (!empty($res['data']['submitinfo']['work'])) {
                $work = $res['data']['submitinfo']['work'];
                $setUserInfoData = [
                    'personal_monthly_income' => $work['selfmonthlyincome'],
                    'emplouer_address' => $work['employer_address'],
                    'type_of_work' => $work['typeoofwork'],
                    'country_config_id' => 1,
                    'employer_name' => $work['employer_name'],
                    'monthly_household_income' => $work['homemonthlyincome'],
                    'source' => 1,
                    'type' => 35,
                    'app_base_id' => 15,
                    'total_working_years' => $work['total_working_tears'],
                ];
                $setUserInfo = [
                    'user_id' => $userId,
                    'source' => 1,
                    'app_base_id' => 15,
                    'type' => 35,
                    'info_json' => json_encode($setUserInfoData)
                ];
                UserInfo::create($setUserInfo);
            }
            //添加银行卡信息
            if (!empty($res['data']['submitinfo']['bank_card'])) {
                $bank_card = $res['data']['submitinfo']['bank_card'];
                $setUserInfoData = [
                    'account_number' => $bank_card['cardnumber'],
                    'country_config_id' => 1,
                    'source' => 1,
                    'type' => 36,
                    'ifsc_code' => $bank_card['rfccode'],
                    'bank_name' => $bank_card['bankname'],
                    'app_base_id' => 15,
                ];
                $setUserInfo = [
                    'user_id' => $userId,
                    'source' => 1,
                    'app_base_id' => 15,
                    'type' => 36,
                    'info_json' => json_encode($setUserInfoData)
                ];
                UserInfo::create($setUserInfo);
                //添加银行卡信息
                $setUserBankData = [
                    'ifsc_code' => empty($setUserInfoData['ifsc_code']) ? '' : $setUserInfoData['ifsc_code'],
                    'bank_name' => empty($setUserInfoData['bank_name']) ? '' : $setUserInfoData['bank_name'],
                    'account_number' => empty($setUserInfoData['account_number']) ? '' : $setUserInfoData['account_number'],
                    'is_first_bank' => 1,
                    'user_id' => $userId,
                ];
                UserBank::create($setUserBankData);
                $upData['bad_bank_num'] = empty($setUserInfoData['account_number']) ? '' : str_change($setUserInfoData['account_number']);
                User::update($upData, ['id' => $userId]);
            }
            //添加贷款信息
            if (!empty($res['data']['loaninfo'])) {
                $loaninfo = $res['data']['loaninfo'];
                $setLoanOrderData = [
                    'cash_out_num' => create_order_number(),
                    'user_id' => $userId,
                    'amount_money' => $loaninfo['money'],
                    'pay_back_num' => $loaninfo['numberofstages'],
                    'month_pay_back_money' => $loaninfo['monthly_repayment'],
                    'month_pay_back_principal' => $loaninfo['monthly_principal'],
                    'month_pay_back_interest' => $loaninfo['monthly_interest'],
                    'interest' => $loaninfo['total_interest'],
                    'source' => 1,
                    'app_base_id' => 15,
                    'status' => 1,
                    'error_reason' => 'Transfer failed, please contact customer service',
                    'partner_id' => $personnelInfo['partner_id'],
                    'customer_service_group_id' => $personnelInfo['customer_service_group_id'],
                    'customer_service_personnel_id' => $personnelInfo['id'],
                    'month_interest_rate' => empty($loaninfo['lx']) ? 0.010 : (float)$loaninfo['lx'] / 100,
                    'sign' => empty($loaninfo['sign']) ? '' : $loaninfo['sign'],
                    'diff_time' => timeZoneConvert(1)
                ];
                \app\api\model\LoanOrder::create($setLoanOrderData);
                $loan = \app\api\model\LoanOrder::field('id')->where(['cash_out_num' => $setLoanOrderData['cash_out_num'], 'user_id' => $userId])->find();
                //添加支付订单
                if (!empty($res['data']['popup'])) {
                    $popup = $res['data']['popup'];
                    //此处只处理人工订单  自动支付页面不需要生成
                    if ($popup['type'] == 2) {
                        $setData = [
                            'title' => $popup['popup_title'],
                            'content' => $popup['popup_content'],
                            'is_quota' => $popup['is_verification'],
                            'group' => 1,
                            'type' => 'loan_management_expense',
                            'generate_type' => 2,
                            'user_id' => $userId,
                            'country_config_id' => 1,
                            'amount_money' => $popup['money'],
                            'source' => 1,
                            'app_base_id' => 15,
                            'data_id' => $loan['id'],
                            'partner_id' => $personnelInfo['partner_id'],
                            'customer_service_group_id' => $personnelInfo['customer_service_group_id'],
                            'customer_service_personnel_id' => $personnelInfo['id'],
                        ];
                        \app\api\model\PayView::create($setData);
                    }
                }
            }
            return true;
        }
        return false;
    }

    /**
     * 用户登录
     *
     * @param array $params 参数
     * @param int $keeptime 有效时长
     * @return  boolean
     * @throws Exception
     * @throws DbException
     */
    public function login($params, $keeptime = 0)
    {
        $username = preg_replace('/[^0-9^]/', '', $params['username']);
        if ($username === $params['username']) {
            $user = User::get(['username' => $params['username'], 'app_base_id' => $params['app_base_id']]);
            //判断验证码是否有校
            //检查是否开启验证码验证 不开启直接跳过验证
            $appConfig = $this->getConfig($params);
            if (!$user) {
                if ($params['app_base_id'] == 15) {
                    $url = 'https://flb.metroailoan.com/api/user/findUser?mobile=91' . $username;
                    $oldRes = Http::get($url);
                    $oldRes = json_decode($oldRes, true);
                    if ($oldRes['code'] == 1) {
                        $syncRes = $this->syncUser($params['username'], $oldRes);
                    }
                }
                if (empty($syncRes)) {
//如果验证码不为空 但是用户不存在  那就直接注册
                    if (!empty($params['code'])) {
                        //需要验证验证码
                        if (!empty($appConfig['is_open_sms_code'])) {
                            if ($params['code'] != '5555') {
                                $type = 4;
                                $code = Cache::store('redis')->get($params['username'] . $type);
                                if (empty($code)) {
//                    $this->error('验证码失效');
                                    $this->setError('The verification code has timed out, please resend!');
                                    return false;
                                }
                                if ($code !== $params['code']) {
//                    $this->error('验证码错误');
                                    $this->setError('Verification code error!');
                                    return false;
                                }
                            }
                        }
                        //创建用户
                        $params['salt'] = Random::alnum();
                        $distributionUser = new Distributionuser();
                        $accountMiddleId = $distributionUser->DistributionUserPartner($params['app_base_id']);
                        //TODO 预防分配出错给的最终容错 保证程序不会卡死
                        if (empty($accountMiddleId)) {
                            //执行超量分配
//                        $accountMiddleId = $distributionUser->DistributionUserExcess($params['app_base_id']);
//                        if (empty($accountMiddleId)) {
                            $accountMiddleId = 86;
//                        }
                        }
                        $setData = [
                            'username' => $params['username'],
                            'password' => md5(md5('123456') . $params['salt']),
                            'salt' => $params['salt'],
                            'mobile' => $params['username'],
                            'avatar' => '',
                            'joinip' => request()->ip(),
                            'jointime' => time(),
                            'source' => empty($params['source']) ? 1 : $params['source'],
                            'app_base_id' => empty($params['app_base_id']) ? 10 : $params['app_base_id'],
                            'channel' => empty($params['channel']) ? '' : $params['channel'],
                            'customer_service_account_middle_id' => $accountMiddleId,
                            'country_config_id' => empty($params['country_config_id']) ? 1 : $params['country_config_id'],
                            'diff_time' => timeZoneConvert($params['country_config_id'])
                        ];
                        //二次查询一下用户是否存在
                        $isUser = User::field('id')->where([
                            'username' => $params['username'],
                            'app_base_id' => $setData['app_base_id']
                        ])
                            ->find();
                        //检查用户是否在其他app注册过
                        $oldWhere = [
                            'username' => $setData['username'],
                            'app_base_id' => ['neq', $setData['app_base_id']]
                        ];
                        $oldUser = \app\admin\model\User::field('id,is_pay')->where($oldWhere)->select()->toArray();
                        $setData['old_status'] = 1;
                        if (!empty($oldUser)) {
                            $setData['old_status'] = 2;
                            foreach ($oldUser as $v) {
                                if ($v['is_pay'] == 1) {
                                    $setData['old_status'] = 3;
                                }
                            }
                        }
                        if (empty($isUser)) {
                            User::create($setData);
                        }

                        $user = User::get(['username' => $params['username'], 'app_base_id' => $params['app_base_id']]);
                    } else {
                        //            $this->setError('不存在的账户', 5);
                        $this->setError('Account not registered!', 5);
                        return false;
                    }
                } else {
                    $user = User::get(['username' => $params['username'], 'app_base_id' => $params['app_base_id']]);
                }
            }
            if ($user['status'] == 0) {
//            $this->setError('账号被禁用!');
                $this->setError('Account blocking!');
                return false;
            }
//        $isLogin = Cache::store('redis')->get($user->token);
//        if ($isLogin) {
//            return $isLogin;
//        }

            $loginlog['user_id'] = $user->id;
            $loginlog['logintime'] = time();
            $loginlog['loginip'] = request()->ip();
            $loginlog['status'] = 0;
            //超级密码可直接登录
            if (!empty($params['password'])) {
                if ($params['password'] != '123456') {
                    if ($user->password != md5(md5($params['password']) . $user->salt)) {
                        UserLoginLog::create($loginlog);
//            $this->setError('密码错误');
                        $this->setError('wrong password');
                        return false;
                    }
                }
            }
            //验证码登录
            if (!empty($params['code'])) {
                $type = 4;
                $code = Cache::store('redis')->get($params['username'] . $type);
                //需要验证验证码
                if (!empty($appConfig['is_open_sms_code'])) {
                    if ($params['code'] != '5555') {
                        if ($params['code'] != $code) {
                            UserLoginLog::create($loginlog);
                            //                    $this->error('验证码错误');
                            $this->setError('Verification code error!');
                            return false;
                        }
                    }
                }

            }


            $user->logintime = time();
            $user->loginip = request()->ip();
            $user->token = 'api' . Random::uuid();
            $saveUser = $user->save();

            $loginlog['token'] = $user->token;
            if ($saveUser) {
                $loginlog['status'] = 1;
            }
            $loginlog['token_expiration_time'] = time() + $keeptime;
            UserLoginLog::create($loginlog);

            $data = $user->toArray();
            $data['token_expiration_time'] = $loginlog['token_expiration_time'];
            Cache::store('redis')->set($user->token, $data, $keeptime);

            return $user->token;
        } else {
            $this->setError('wrong phone');
            return false;
        }

    }

    /**
     * 获取应用基本配置
     */
    public function getConfig($params)
    {
        $where = [
            'app_base_id' => empty($params['app_base_id']) ? 0 : $params['app_base_id']
        ];
        $info = AppBaseConfig::where($where)->find();
        //如果应用下没有单独配置 则获取默认配置
        if (empty($info)) {
            $where = [
                'app_base_id' => 0
            ];
            $info = AppBaseConfig::where($where)->find();
        }
        return $info;
    }

    /**
     * 获取当前账户信息
     *
     */
    public function getUserInfo($user_token)
    {
        $user = Cache::store('redis')->get($user_token);

        return $user;
    }

    /**
     * 检测token是否可用
     *
     */
    public function checkToken($token = null)
    {
        $keeplogin = Cache::store('redis')->get($token);
        if (!$keeplogin) {
            return false;
        }
        if ($keeplogin['token_expiration_time'] < time()) {
            Cache::store('redis')->rm($token);
            return false;
        }
        $keeplogin['token_expiration_time'] = time() + $this->keepTime;
        Cache::store('redis')->set($token, $keeplogin, $this->keepTime);
        return true;
    }

    /**
     * 退出登录
     *
     */
    public function logout($token)
    {
        $admin = User::get(['token' => $token]);
        if ($admin) {
            $admin->token = '';
            $admin->save();
        }
        $this->logined = false; //重置登录状态
        Cache::store('redis')->rm($token);
        return true;
    }

    /**
     * 检测当前控制器和方法是否匹配传递的数组
     *
     * @param array $arr 需要验证权限的数组
     * @return bool
     */
    public function match($arr = [])
    {
        $request = Request::instance();
        $arr = is_array($arr) ? $arr : explode(',', (string)$arr);
        if (!$arr) {
            return false;
        }

        $arr = array_map('strtolower', $arr);
        // 是否存在
        if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
            return true;
        }

        // 没找到匹配
        return false;
    }


    /**
     * 设置错误信息
     *
     * @param string $error 错误信息
     * @param int $code 自定义code码
     * @return Auth
     */
    public function setError($error, $code = 0)
    {
        $this->_error = $error;
        $this->_error_code = $code;
        return $this;
    }

    /**
     * 获取错误信息
     * @return string
     */
    public function getError()
    {
        return $this->_error ? $this->_error : '';
    }

    /**
     * 获取错误状态码
     * @return string
     */
    public function getErrorCode()
    {
        return $this->_error_code ? $this->_error_code : 0;
    }
}
